//
// Created by 67678 on 2023/3/17.
//

#include "dateBase.h"
#include <mutex>
#include <arpa/inet.h>
#include <fmt/format.h>
#include "hiredis.h"
#include "log.h"

namespace dateBase {

DateBase::DateBase() {
    log("DateBase opening!");
    const char *ip = "172.30.174.27";
    int port = 6379;
    conn_ = redisConnect(ip, port);
    if (conn_->err != 0) {
        log("redis server connect failed");
        throw runtime_error("redis server connect failed");
    }
    log("DateBase successfully opened!");
}

DateBase::~DateBase() {
    log("DateBase closing!");
    redisFree(conn_);
}

std::string DateBase::set(std::string_view key, std::string_view value) {
    string cmd = fmt::format("set {} {}", key, value);
    unique_lock ul(mx_);
    redisReply *reply = static_cast<redisReply *>(redisCommand(conn_, cmd.c_str()));
    ul.unlock();
    freeReplyObject(reply);
    return "OK";
}

std::string DateBase::get(std::string_view key) {
    string cmd = fmt::format("get {} ", key);
    unique_lock ul(mx_);
    redisReply *reply = static_cast<redisReply *>(redisCommand(conn_, cmd.c_str()));
    ul.unlock();
    string ret;
    if (reply->str != nullptr)ret.append(reply->str);
    freeReplyObject(reply);
    return ret;
}


}